<script>
   export default{
     name: "User",
     data(){
       return{
         tableData: [],
         pageNum: 1, // 当前的页码
         pageSize: 7, // 每页的条数
         total: 0,
         username: '',
         name: '',
         userFormVisible: false,
         form: {},
         ids: {},
         user: JSON.parse(localStorage.getItem('honey-user') ||
         '{}'),
         rules: {
           username: [
             {required: true, message: '请输入用户名', trigger: 'blur'},
             {min: 3, max: 5, message: '长度在 5 到 10 个字符', trigger: 'blur'}
           ],
           name: [
             {required: true, message: '请输入姓名', trigger: 'blur'},
             {min: 2, max: 5, message: '长度在 5 到 10 个字符', trigger: 'blur'}
           ]
         }
       }
     },
     created(){
       this.load()
     },
     methods:{
       //分页查询
       load(pageNum){
         if(pageNum){
           this.pageNum = pageNum
         }
         this.$request.get('/user/selectByPage',{
           params:{
             username: this.username,
             name: this.name,
             pageNum: this.pageNum,
             pageSize: this.pageSize,
           }
         }).then(res =>{
           this.tableData = res.data.records;
           this.total = res.data.total
         })
       },
       handleCurrentChange(pageNum){
         this.pageNum = pageNum
         this.load(pageNum)
       },
       handleSizeChange(){
         this.pageSize = pageSize
       },
       reset(){
         this.username = '';
         this.name = '';
         this.load(1)
       },
       handleAvatarSuccess(response, file, fileList){
         //把user的头像替换为上传图片的链接
         this.form.avatar = response.data
       },
       save(){
        this.$refs.formRef.validate(valid =>{
          if(valid){
            this.$request({
              url: this.form.id ? '/user/update' : '/user/add',
              method: this.form.id ? 'put' : 'post',
              data: this.form
            }).then(res =>{
              if(res.code === '200'){
                //表示保存成功
                this.$message.success('保存成功')
                this.userFormVisible = false
                this.load(1)
              }else{
                //保存失败，弹出错误信息
                this.$message.error(res.msg)
              }
            })
          }
        })
       },
       handleAdd(){
        this.form = { role: 'USER'};
        this.userFormVisible = true
       },
       handleEdit(row){
         //给对象赋值
          this.form = JSON.parse(JSON.stringify(row));
          //打开弹窗
          this.userFormVisible = true
       },
       handleDelete(id){
         if(id === this.user.id){
           this.$message.warning('不能删除自己')
           return
         }
         this.$confirm("确定要删除吗？", "确定删除", {type: "warning"}).then(res =>{
           this.$request.delete('/user/delete/' + id).then(res =>{
             if(res.code === '200'){
               this.$message.success('删除成功')
               this.load(1)
             }else{
               this.$message.error(res.msg)
             }
           })
         }).catch(() =>{})
       },
       //当前选中所有的行数据
       handleSelectionChange(rows){
         this.ids = rows.map(v => v.id);
       },
       deleteBatch(){
         if(this.ids.includes(this.user.id)){
           this.$message.warning('不能删除自己')
           return
         }
         if(this.ids.length === 0){
           this.$message.warning('请先选择要删除的数据')
           return
         }
         this.$confirm("确定要批量删除数据吗？", "确定删除", {type: "warning"}).then(res =>{
           this.$request.delete('/user/delete/batch',{
             data: this.ids
           }).then(res =>{
             if(res.code === '200'){
               this.$message.success('删除成功')
               this.load(1)
             }else{
               this.$message.error(res.msg)
             }
           })
         }).catch(() =>{})
       }
     }
   }
</script>

<template>
  <div>
    <div style="display: flex; justify-content: center">
      <el-input style="width: 200px" placeholder="查询用户名" v-model="username"></el-input>
      <el-input style="width: 200px; margin: 0 10px" placeholder="查询姓名" v-model="name"></el-input>
      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="success" @click="reset">重置</el-button>
    </div>
    <div style="display: flex; justify-content: center;margin: 20px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="deleteBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue',color: '#666'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="55" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center"></el-table-column>
      <el-table-column prop="name" label="姓名" align="center"></el-table-column>
      <el-table-column prop="phone" label="电话" align="center"></el-table-column>
      <el-table-column prop="email" label="电子邮件" align="center"></el-table-column>
      <el-table-column prop="address" label="地址" align="center"></el-table-column>
      <el-table-column prop="avatar" label="头像" align="center">
        <template v-slot="scope">
          <el-image v-if="scope.row.avatar" :src="scope.row.avatar"
                    style="width: 50px; height: 50px;border-radius: 20px" :preview-src-list="[scope.row.avatar]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="身份" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="warning" plain @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <span class="demonstration">完整功能</span>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="用户信息" :visible.sync="userFormVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 30px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="输入电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" :rows="3" v-model="form.address" placeholder="输入地址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-radio-group label="身份" v-model="form.role">
            <el-radio label="ADMIN"></el-radio>
            <el-radio label="USER"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像">
            <el-upload
                accept="jpg"
                action="http://localhost:8080/file/upload"
                :on-success="handleAvatarSuccess"
                :file-list="form.avatar ? [form.avatar] : []"
                :show-file-list="true"
                list-type="picture"
                :headers="{token: user.token}">
              <el-button size="mini" type="primary" style="margin: 10px 0;">上传文件</el-button>
            </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="userFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
el-table el-table-column{
  align-items: center;
}
</style>